<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="300px">
        <el-form-item label="请选择角色">
          <el-tree style="max-width: 600px" :data="RoleData" node-key="id" @node-click="handleNodeClick" />
        </el-form-item>
      </el-aside>
      <el-aside width="300px">
        <el-form-item label="请选择菜单">
          <el-tree style="max-width: 600px" v-model="RoleMenu.MenuIds" ref="treeRef" :data="MenuData" default-expand-all
            show-checkbox node-key="id" />
        </el-form-item>
      </el-aside>
    </el-container>
    <el-footer>
      <el-button style="margin-left: 550px;" type="primary" @click="AddMenuRole()" plain>保存</el-button>
    </el-footer>
  </div>
</template>
<script lang="ts" setup>
import http from '@/http/axiosHelper';
import { onMounted, ref } from 'vue';
import { type ElTree, type TreeInstance, type CheckboxValueType, ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
onMounted(() => {
  ShowRoleTree()
  ShowMenuTree(0)
})
//角色
const RoleData = ref([])
const ShowRoleTree = () => {
  http.get("/api/RoleMenu/GetRoleTree").then(res => {
    RoleData.value = res.data.Data
  })
}
const handleNodeClick = (data: any) => {
  RoleMenu.value.RoleId = data.id
  ShowMenuTree(data.id)
  FindMenuRole(data.id)
}
//菜单
const MenuData = ref([])
const ShowMenuTree = (id:any) => {
  http.get("/api/RoleMenu/GetMenuTree",{params:{RoleId:id}}).then(res => {
    MenuData.value = res.data.Data
  })
}
//添加
const RoleMenu = ref({
  "RoleId": "",
  "MenuId": "",
  "MenuIds": []
})
const treeRef = ref<TreeInstance>()
const AddMenuRole = () => {
  var checkTree = treeRef.value?.getCheckedKeys(false)
  RoleMenu.value.MenuId = checkTree?.toString()??''
  console.log(RoleMenu.value);
  http.post("/api/RoleMenu/CreateRoleMenu", RoleMenu.value).then(res => {
    if (res.data.Code == 200) {
      ElMessage.success(res.data.Message)
      ShowRoleTree()
      ShowMenuTree(RoleMenu.value.RoleId)
      FindMenuRole(RoleMenu.value.RoleId)
    }
    else {
      ElMessage.warning(res.data.Message)
    }
  })
}
const FindMenuRole = (id: any) => {
  RoleMenu.value.MenuId = ""
  RoleMenu.value.MenuIds = []
  http.get("/api/RoleMenu/FindRoleMenu", { params: { RoleId: id } }).then(res => {
    if (res.data.Data.length == 0) {
      treeRef.value?.setCheckedKeys([], true);
      return
    }
    res.data.Data.forEach((ss:any)=>{
      RoleMenu.value.MenuIds.push(ss.MenuId as never)
    })
    treeRef.value?.setCheckedKeys(RoleMenu.value.MenuIds, false);
  })
}
</script>